package crons

import (
	"context"
	"devops-super/internal/dao"
	"devops-super/internal/model/do"
	"devops-super/internal/model/entity"
	"devops-super/internal/service"
	"github.com/gogf/gf/v2/os/gtime"
)

func (s *sCron) DoClearIoTData(ctx context.Context) (err error) {
	cols := dao.AppDistributeTables.Columns()
	pageSize := 2000
	page := 1
	for {
		pageOffset := (page - 1) * pageSize
		var rows []*entity.AppDistributeTables
		err = dao.AppDistributeTables.Ctx(ctx).
			Where(cols.ExpireTime+" < ", gtime.Now().Unix()).
			Where(cols.IsExpire, 1).
			Offset(pageOffset).Limit(pageSize).Scan(&rows)
		if err != nil {
			return
		}
		for _, row := range rows {
			//矫正： 过期时间必须比结束时间要大7天 也就是至少比最迟的时间点保留7天
			if row.ExpireTime-7*24*3600 < int64(row.TimeEnd) {
				_, err = dao.AppDistributeTables.Ctx(ctx).WherePri(row.Id).Update(do.AppDistributeTables{
					ExpireTime: row.TimeEnd + 7*24*3600,
					UpdatedAt:  gtime.Now(),
				})
				if err != nil {
					return
				}
				continue
			}
			err = service.DistributeTables().Del(ctx, int(row.Id))
			if err != nil {
				continue
			}
		}
		if len(rows) < pageSize {
			break
		}
		page++
	}
	return

}
